//
//  InformationDetailViewController.m
//  gamebox_qpp
//
//  Created by 赵隆杰 on 2021/12/30.
//

#import "InformationDetailViewController.h"
#import "InformationDetailApi.h"
#import "InformationDetailStateApi.h"
#import "InformationDetailSetStateApi.h"

@interface InformationDetailViewController ()

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UIImageView *gameImage;
@property (weak, nonatomic) IBOutlet UILabel *contentLabel;
@property (weak, nonatomic) IBOutlet UILabel *descLabel;

@property (weak, nonatomic) IBOutlet UIButton *btn1;
@property (weak, nonatomic) IBOutlet UIButton *btn2;


@property (nonatomic, strong) InformationModel *detail;
@property (nonatomic, assign) NSInteger state;

@end

@implementation InformationDetailViewController

- (InformationModel *)detail
{
    if (!_detail) {
        _detail = [[InformationModel alloc] init];
    }
    return _detail;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.centerTitle.text = @"详情";
    self.view.backgroundColor = [UIColor whiteColor];
    
//    [self.btn1 setBackgroundImage:[UIImage imageWithColor:[UIColor clearColor]] forState:UIControlStateNormal];
//    [self.btn1 setBackgroundImage:[UIImage imageWithColor:kThemeColor] forState:UIControlStateSelected];
//    self.btn1.layer.cornerRadius = 5;
//    self.btn1.layer.masksToBounds = YES;
        
    [self fetchData];
    [self fetchStateData];
}

- (void)setModel:(InformationModel *)model
{
    _model = model;
}

- (void)fetchData
{
    InformationDetailApi *api = [[InformationDetailApi alloc] initWithInformationId:_model.detailId];
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        if (api.success) {
            self.detail = [InformationModel mj_objectWithKeyValues:api.res];
            [self reloadUI];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
    }];
    
    
}

- (void)fetchStateData
{
    if (![LocalData fetchUserInfo]) {
        return;
    }
    InformationDetailStateApi *api = [[InformationDetailStateApi alloc] initWithInformationId:_model.detailId];
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        if (api.success) {
            self.state = api.state;
            if (self.state == 1) {
                self.btn1.selected = YES;
            } else {
                self.btn1.selected = NO;
            }
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
    }];
    
    
}

- (void)reloadUI
{
    self.titleLabel.text = [NSString stringWithFormat:@"%@", _model.messageName];
    [self.gameImage yy_setImageWithURL:[NSURL URLWithString:_model.messagePic] placeholder:placeholder_image];
    self.timeLabel.text = [NSDate timeStringToInterval:_detail.createTime.doubleValue dataFormat:@"yyyy-MM-dd HH:mm"];
    self.contentLabel.text = [_detail.detail.origin getLinefeed];
        
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:_detail.detail.detailContent attributes:nil];
    
    NSMutableArray *indexArray = [NSMutableArray array];
    NSString *content = [_detail.detail.detailContent mutableCopy];
    while ([content containsString:@"\n\r\n\r"]) {
        NSRange range = [content rangeOfString:@"\n\r\n\r"];
        [indexArray addObject:@(range.location+range.length-2)];
        content = [content substringWithRange:NSMakeRange(range.location+range.length-2, content.length-range.location-range.length-2)];
    }
    
    for (NSInteger i = 0; i < _detail.detail.messageImgs.count; i++) {
        
        if (indexArray.count > i) {
            
            ImageModel *imageModel = _detail.detail.messageImgs[i];
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageModel.imgUrl]]];
            // 创建图片图片附件
            NSTextAttachment *attach = [[NSTextAttachment alloc] init];
            attach.image = image;
            if (image.size.width > image.size.height) {
                attach.bounds = CGRectMake(0, 0, SL_WINDOW_WIDTH - 40, 8.0/15 * (SL_WINDOW_WIDTH - 40));
            } else {
                attach.bounds = CGRectMake(0, 0, SL_WINDOW_WIDTH - 40, 15.0/8 * (SL_WINDOW_WIDTH - 40));
            }
            
            NSAttributedString *attachString = [NSAttributedString attributedStringWithAttachment:attach];
            
            NSInteger index = [indexArray[i] integerValue];
            //将图片插入到合适的位置
            [string insertAttributedString:attachString atIndex:index];
        }
    }
    
    self.descLabel.attributedText = string;
    
}

- (void)hdjNaviUI
{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnClick)];
}

- (void)rightBtnClick
{
    if (![LocalData fetchUserInfo]) {
        [[AppLogic sharedInstance] presentLoginVC];
        return;
    }
    NSString *title = [LocalData fetchUserInfo].nickname;
    if (!title.length) {
        title = [LocalData fetchUserInfo].account;
    }
    //1.设定分享的内容,比如:
    NSString *shareTitle = [NSString stringWithFormat:@"用户%@分享了资讯 - %@",title, _model.messageName];

    UIImage *shareImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_model.messagePic]]];
    
    NSArray *activityItems = @[shareTitle, shareImage]; // 必须要提供url 才会显示分享标签否则只显示图片

    //2.创建分享的控制器
    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
    
    //3.设定不想显示的平台和功能
//    activityVC.excludedActivityTypes = [self excludetypes];

    //4. 设置操作回调,用户点击 菜单按钮后事件执行完成会回调这个block
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {

            if (completed) {
                NSLog(@"分享成功");
            }else{
                NSLog(@"分享失败");
            }
        };

    //5.显示分享菜单
    [self presentViewController:activityVC animated:YES completion:nil];
     
    
}

- (IBAction)likeBtnClick:(UIButton *)sender {
    if (![LocalData fetchUserInfo]) {
        [[AppLogic sharedInstance] presentLoginVC];
        return;
    }
    
    NSInteger tag = sender.tag;
    if (tag == 0) {
        //不感兴趣
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [self performSelector:@selector(testMethod1) withObject:@"aaa" afterDelay:.3];
    } else {
        //喜欢
        NSNumber *number = (self.state == 1) ? @0 : @1;
        InformationDetailSetStateApi *api = [[InformationDetailSetStateApi alloc] initWithInformationId:_model.detailId state:number];
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            if (api.success) {
                [self fetchStateData];
            }
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        }];
    }
    
    
    
}

- (void)testMethod1
{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    self.btn2.selected = !self.btn2.selected;
}


@end
